package com.fs.console.base.vo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.BeforeFilter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ACE
 * @desc
 * @creationTime 2019-03-08 14:37
 * @projectName gps-root
 * @packageName com.fs.base.vo
 */
@Data
public class DataGrid {
    /**
     * 是否树形表格
     */
    private Boolean  isTreeGrid = false;
    /**
     *树形子关系字段
     */
    private String treeId;
    /**
     *树形父关系字段
     */
    private String treePid;
    /**
     * 总记录
     */
    private Long total = 0L ;
    /**
     * 单页数据集
     */
    private List<?> rows;
    /**
     * 当前实体类名（预留使用）
     */
    private String className;

    public DataGrid() {
    }

    public DataGrid(Long total, List<?> rows){
        this.total = total;
        this.rows = rows;
    }

    public DataGrid(HttpServletRequest request){
        if(StringUtils.isNoneBlank(request.getParameter("isTreeGrid"))){
            this.isTreeGrid = Boolean.valueOf(request.getParameter("isTreeGrid"));
        }
        if(StringUtils.isNoneBlank(request.getParameter("treeId"))){
            this.treeId = request.getParameter("treeId");
        }
        if(StringUtils.isNoneBlank(request.getParameter("treePid"))){
            this.treePid = request.getParameter("treePid");
        }
    }

    /**
     * 适配分页grid
     * @param page
     * @return
     */
    public static <K> DataGrid gridBuilder(Page<K> page){
        return new DataGrid(page.getTotal(),  page.getRecords());
    }

    public static <K> DataGrid gridBuilder(IPage page){
        return new DataGrid(page.getTotal(),  page.getRecords());
    }
    /**
     * 适配一般集合
     * @param rows
     * @return
     */
    public static <K> DataGrid gridBuilder(List<K> rows){
        Long len =  Long.parseLong(rows.size() + "" );
        return new DataGrid(len,  rows);
    }

    /**
     * 树形格式化1
     * @param rows
     * @param grid
     * @return
     */
    public static <K> DataGrid treeBuilder(List<K> rows, DataGrid grid){
        return treeBuilder(rows, grid.getTreeId(),grid.getTreePid());
    }

    /**
     * 树形格式化2
     * @param rows
     * @param treeId 树形主键字段
     * @param treePid 树形主键对应的父亲节点字段
     * @return
     */
    public static <K> DataGrid treeBuilder(List<K> rows, String treeId, String treePid){
        List<Tree> treeList = new ArrayList<Tree>();
        List<JSONObject> jsonList = new ArrayList<JSONObject>();
        String json = JSON.toJSONString(rows);
        JSONArray array = JSON.parseArray(json);
        String treeIdValue = null ,treePidValue = null;
        for(int i=0,len=array.size();i<len;i++){
            JSONObject item = array.getJSONObject(i);
            treeIdValue = item.getString(treeId);
            treePidValue = item.getString(treePid)==null? "" : item.getString(treePid);
            Tree tree = new Tree(treeIdValue, treePidValue, item);
            treeList.add(tree);
        }
        List<Tree> nodeList = new ArrayList<Tree>();
        for(Tree node1 : treeList){
            boolean mark = false;
            for(Tree node2 : treeList){
                if(node1.getTreePid()!=null && node1.getTreePid().equals(node2.getTreeId())){
                    mark = true;
                    if(node2.getChildren() == null) {
                        node2.setChildren(new ArrayList<Tree>());
                    }
                    node2.getChildren().add(node1);
                    break;
                }
            }
            if(!mark){
                nodeList.add(node1);
            }
        }
        BeforeFilter treeFilter = new BeforeFilter () {
            @SuppressWarnings("unchecked")
            @Override
            public void writeBefore(Object object) {
                String key = "o";
                JSONObject json = (JSONObject) JSON.toJSON(object);
                if(json.containsKey(key)){
                    JSONObject self = json.getJSONObject(key);
                    Map<String,Object> map = JSONObject.toJavaObject(self, Map.class);
                    for(String m: map.keySet()){
                        writeKeyValue(m, map.get(m));
                    }
                }
            }
        };
        String tempJson = null;
        for(Tree tree: nodeList){
            tempJson =  JSONObject.toJSONString(tree, treeFilter);
            JSONObject tt = JSON.parseObject(tempJson);
            jsonList.add(tt);
        }
        return gridBuilder(jsonList);
    }
}